<?php

namespace App\Http\Api\Services;

use App\Exceptions\InvalidRequestException;
use App\Http\Models\Mate;
use App\Http\Services\BaseService;
use Illuminate\Support\Facades\DB;


class MateService extends BaseService
{
    /*
     * 有好货列表id采集
     * */
    public function listStore($attributes = [])
    {
        $platform = $attributes['platform'] ?? 0;
        $list = $attributes['data'];
        $content_ids = json_decode($list, true);
        $add_content_ids = [];
        if (!empty($content_ids)) {
            $datebase_content_ids = Mate::whereIn('content_id', $content_ids)->get()->pluck('content_id')->toArray();
            foreach ($content_ids as $content_id) {
                if (!in_array($content_id, $datebase_content_ids)) {
                    $add_content_ids[] = [
                        'content_id' => $content_id,
                        'platform' => $platform,
                        'created_at' => date('Y-m-d H:i:s',time())
                    ];
                }
            }
        }
        $res = Mate::insert($add_content_ids);
        return $res;
    }

    /*
     * 材料采集
     * */
    public function store($attributes = [])
    {
        //平台区分
        switch ($attributes['platform']){
            // 0 有好货
            case 0:
                $merge_data = $this->getValidAttributes($attributes);
                break;
            // 1 头条号
            case 1:
                $merge_data = $attributes;
                break;
        }

        $content_id = (string)$merge_data['content_id'];
        $article = [];
        $article['content_id'] = $content_id;
        if (!empty($merge_data['main_info'])) {
            $main_info = $merge_data['main_info'];
            $article['title'] = !empty($main_info['title']) ? $main_info['title'] : '';
            $article['summary'] = !empty($main_info['summary']) ? $main_info['summary'] : '';
            $article['cover'] = !empty($main_info['cover']) ? $main_info['cover'] : '';
            $article['pub_time'] = !empty($main_info['pub_time']) ? $main_info['pub_time'] : '';
            $article['tags'] = !empty($main_info['tags']) ? $main_info['tags'] : '';
        }

        //条目
        $article_items = $merge_data['contents'];

        if(count($article_items) == 0){
            Mate::where('content_id',$content_id)->delete();
            throw new InvalidRequestException('没有内容 作废');
        }


        //存储过程
        DB::beginTransaction();
        try {
            $item = Mate::where('content_id', $article['content_id'])->first();
            $item->title = $article['title'];
            $item->cover = $article['cover'];
            $item->summary = $article['summary'];
            $item->tags = $article['tags'];
            $item->pub_time = $article['pub_time'];
            $item->flag = 1;
            $item->save();
            $item->items()->createMany($article_items);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            throw new InvalidRequestException($e->getMessage());
        }
        return $item;
    }


    public function getValidAttributes($attributes)
    {
        $contents = [];
        $main_info = [];
        if (empty($attributes['content_id'])) {
            throw new InvalidRequestException('缺少content_id');
        }
        if (!empty($attributes['data'])) {
            $data = $attributes['data'];
            $data = json_decode($data);
            if (!empty($data->models)) {
                $models = $data->models;
                if (!empty($models->tags)) {
                    $tags = $models->tags;
                    if (is_array($tags)) {
                        $str = '';
                        foreach ($tags as $tag) {
                            if (!empty($tag->name)) {
                                $tag_name = $tag->name;
                                if ($str != '') {
                                    $str = $str . ',' . $tag_name;
                                } else {
                                    $str = $tag_name;
                                }
                            }
                        }
                        $main_info['tags'] = $str;
                    }
                }
                if (!empty($models->content)) {
                    //content层
                    $content = $models->content;

                    //summary
                    if (!empty($content->summary)) {
                        $main_info['summary'] = $content->summary;
                    }
                    //pub_time
                    if (!empty($content->gmtCreate)) {
                        $main_info['pub_time'] = $content->gmtCreate.':00';
                    }

                    //封面
                    if (!empty($content->mixCover)) {
                        $mixCover = $content->mixCover;
                        if (!empty($mixCover->picDTO)) {
                            $picDTO = $mixCover->picDTO;
                            if (!empty($picDTO->picHeight)) {
                                $picWidth = $picDTO->picWidth;
                                if ($picWidth > 400) {
                                    if (!empty($picDTO->picUrl)) {
                                        $picUrl = $picDTO->picUrl;
                                        $main_info['cover'] = $picUrl;
                                    }
                                }
                            }
                        }
                    }
                    //标题
                    if (!empty($content->title)) {
                        $title = $content->title;
                        $main_info['title'] = trim($title);
                    }
                    //richText
                    if (!empty($content->richText)) {
                        $richText = $content->richText;
                        //richText有东西的情况
                        if (count($richText) > 0) {
                            $i = 1;
                            foreach ($richText as $rich_text) {
                                if (!empty($rich_text->resource)) {
                                    $resource = $rich_text->resource;
                                    if (!empty($resource[0])) {
                                        $rec = $resource[0];
                                        if (!empty($rec->entityType)) {
                                            $entityType = $rec->entityType;
                                            if ($entityType == 'ResourceText') {
                                                if (!empty($rec->text)) {
                                                    $text = $rec->text;
                                                    $contents[] = [
                                                        'content' => $text,
                                                        'type' => 1,
                                                        'order_by' => $i
                                                    ];
                                                    $i++;
                                                }
                                            }
                                            if ($entityType == 'ResourcePic') {
                                                if (!empty($rec->picture)) {
                                                    $picture = $rec->picture;

                                                    if (!empty($picture->picDesc)) {
                                                        $contents[] = [
                                                            'content' => $picture->picDesc,
                                                            'type' => 1,
                                                            'order_by' => $i
                                                        ];
                                                        $i++;
                                                    }
                                                    if (!empty($picture->picUrl)) {
                                                        $contents[] = [
                                                            'content' => $picture->picUrl,
                                                            'type' => 2,
                                                            'order_by' => $i
                                                        ];
                                                        $i++;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }

                            }
                        }
                    }
                }
            }
        }

        return [
            'content_id' => $attributes['content_id'],
            'contents' => $contents,
            'main_info' => $main_info,
        ];

    }

    public function contentId($platform = 0)
    {
        $item = Mate::where('flag', 0)
            ->where('platform',$platform)
            ->inRandomOrder()
            ->first();
        $content_id = null;
        if($item['content_id']){
            $content_id = $item['content_id'];
            $item->flag = 1;
            $item->save();
        }
        return $content_id;
    }
}
